import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { getUserDesigns, deleteDesign, updateDesignPublicStatus, Design } from '../services/design';

interface DesignGalleryProps {
  onCreateDesign: () => void;
}

const DesignGallery: React.FC<DesignGalleryProps> = ({ onCreateDesign }) => {
  const [designs, setDesigns] = useState<Design[]>([]);
  const [completedDesigns, setCompletedDesigns] = useState<Design[]>([]);
  const [galleryLoading, setGalleryLoading] = useState(false);
  const [galleryError, setGalleryError] = useState<string | null>(null);
  const [selectedDesign, setSelectedDesign] = useState<Design | null>(null);
  const { user } = useAuth();
  const history = useHistory();

  const loadDesigns = async () => {
    if (!user) {
      setGalleryError('User not authenticated');
      return;
    }

    setGalleryLoading(true);
    setGalleryError(null);
    
    try {
      const response = await getUserDesigns();
      const allDesigns = response.data?.designs || [];
      setDesigns(allDesigns);
      
      // 过滤出成功完成的设计
      const successfulDesigns = allDesigns.filter(design => design.status === 'completed');
      setCompletedDesigns(successfulDesigns);
    } catch (error: any) {
      console.error('Failed to load designs:', error);
      setGalleryError(error.message || 'Failed to load designs');
      setDesigns([]);
      setCompletedDesigns([]);
    } finally {
      setGalleryLoading(false);
    }
  };

  useEffect(() => {
    if (user) {
      loadDesigns();
    }
  }, [user]);

  const handleDeleteDesign = async (designId: string) => {
    if (!user) return;
    
    try {
      await deleteDesign(designId);
      const updatedDesigns = designs.filter(d => d.id !== designId);
      setDesigns(updatedDesigns);
      setCompletedDesigns(updatedDesigns.filter(d => d.status === 'completed'));
      setSelectedDesign(null);
    } catch (error: any) {
      console.error('Failed to delete design:', error);
    }
  };

  const handleTogglePublicStatus = async (designId: string, currentStatus: boolean, event: React.MouseEvent) => {
    // 阻止事件冒泡，避免触发设计详情弹窗
    event.stopPropagation();
    
    if (!user) return;
    
    try {
      const response = await updateDesignPublicStatus(designId, !currentStatus);
      if (response.success) {
        // 更新本地状态
        const updatedDesigns = designs.map(d => 
          d.id === designId ? { ...d, isPublic: !currentStatus } : d
        );
        setDesigns(updatedDesigns);
        setCompletedDesigns(updatedDesigns.filter(d => d.status === 'completed'));
        
        // 如果当前选中的设计是被更新的设计，也要更新选中的设计状态
        if (selectedDesign && selectedDesign.id === designId) {
          setSelectedDesign({ ...selectedDesign, isPublic: !currentStatus });
        }
      }
    } catch (error: any) {
      console.error('Failed to update public status:', error);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'bg-green-100 text-green-800';
      case 'processing':
        return 'bg-yellow-100 text-yellow-800';
      case 'failed':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div className="mb-6">
          <h2 className="text-2xl font-bold text-gray-900 mb-2">My Design Gallery</h2>
          <p className="text-gray-600">View and manage your successful AI-generated room designs</p>
        </div>

        {galleryLoading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">Loading designs...</p>
          </div>
        ) : galleryError ? (
          <div className="text-center py-12">
            <h3 className="text-lg font-medium text-red-600 mb-2">Error</h3>
            <p className="text-gray-600 mb-4">{galleryError}</p>
            <div className="space-x-4">
              <button
                onClick={loadDesigns}
                className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
              >
                Retry
              </button>
              {(galleryError.includes('登录') || galleryError.includes('认证')) && (
                <button
                  onClick={() => history.push('/login')}
                  className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors"
                >
                  Log In Again
                </button>
              )}
            </div>
          </div>
        ) : !Array.isArray(completedDesigns) || completedDesigns.length === 0 ? (
          <div className="text-center py-12">
            <div className="text-gray-400 mb-4">
              <svg className="mx-auto h-24 w-24" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </div>
            <h3 className="text-lg font-medium text-gray-900 mb-2">No Completed Designs Yet</h3>
            <p className="text-gray-600 mb-6">
              {designs.length > 0 
                ? 'You have designs in progress. Completed designs will appear here once finished.' 
                : 'Start creating your first AI-generated room design!'}
            </p>
            <button
              onClick={onCreateDesign}
              className="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 transition-colors"
            >
              Create Design
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {Array.isArray(completedDesigns) && completedDesigns.map((design) => (
              <motion.div
                key={design.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5 }}
                className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow cursor-pointer border border-gray-200"
                onClick={() => setSelectedDesign(design)}
              >
                <div className="aspect-w-16 aspect-h-9 bg-gray-200">
                  {design.generatedImageUrl ? (
                    <img
                      src={design.generatedImageUrl}
                      alt={`${design.designStyle || 'Unknown'} ${design.roomType || 'Unknown'} design`}
                      className="w-full h-48 object-cover"
                    />
                  ) : (
                    <div className="w-full h-48 bg-gray-200 flex items-center justify-center">
                      <span className="text-gray-400">No Image</span>
                    </div>
                  )}
                </div>
                <div className="p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                      Completed
                    </span>
                    <span className="text-sm text-gray-500">{design.creditsUsed} Credits</span>
                  </div>
                  <h3 className="font-semibold text-gray-900 mb-1">
                    {design.designStyle ? (design.designStyle.charAt(0).toUpperCase() + design.designStyle.slice(1)) : 'Unknown Style'} {design.roomType ? (design.roomType.charAt(0).toUpperCase() + design.roomType.slice(1)) : 'Unknown Room'}
                  </h3>
                  <p className="text-sm text-gray-600 mb-2 line-clamp-2">{design.prompt}</p>
                  <p className="text-xs text-gray-500">{formatDate(design.createdAt)}</p>
                  
                  {/* 公开状态开关 */}
                  <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-100">
                    <span className="text-xs text-gray-600">Public</span>
                    <button
                      onClick={(e) => handleTogglePublicStatus(design.id, design.isPublic || false, e)}
                      className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${
                        design.isPublic ? 'bg-blue-600' : 'bg-gray-200'
                      }`}
                    >
                      <span
                        className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform ${
                          design.isPublic ? 'translate-x-5' : 'translate-x-1'
                        }`}
                      />
                    </button>
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        )}
      </div>

      {/* Design Detail Modal */}
      {selectedDesign && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-2xl font-bold text-gray-900">
                  {selectedDesign.designStyle ? (selectedDesign.designStyle.charAt(0).toUpperCase() + selectedDesign.designStyle.slice(1)) : 'Unknown Style'} {selectedDesign.roomType ? (selectedDesign.roomType.charAt(0).toUpperCase() + selectedDesign.roomType.slice(1)) : 'Unknown Room'}
                </h2>
                <button
                  onClick={() => setSelectedDesign(null)}
                  className="text-gray-400 hover:text-gray-600 transition-colors"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Original Image */}
                <div>
                  <h3 className="text-lg font-semibold mb-2">Original Image</h3>
                  <img
                    src={selectedDesign.originalImageUrl}
                    alt="Original room"
                    className="w-full rounded-lg shadow-md"
                  />
                </div>

                {/* Generated Image */}
                <div>
                  <h3 className="text-lg font-semibold mb-2">Generated Design</h3>
                  {selectedDesign.generatedImageUrl ? (
                    <img
                      src={selectedDesign.generatedImageUrl}
                      alt="Generated design"
                      className="w-full rounded-lg shadow-md"
                    />
                  ) : (
                    <div className="w-full h-64 bg-gray-200 rounded-lg flex items-center justify-center">
                      <span className="text-gray-400">No Generated Image</span>
                    </div>
                  )}
                </div>
              </div>

              <div className="mt-6 space-y-4">
                <div>
                  <h4 className="font-semibold text-gray-900">Prompt</h4>
                  <p className="text-gray-600">{selectedDesign.prompt}</p>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <span className="font-semibold text-gray-900">Status:</span>
                    <span className="ml-2 px-2 py-1 rounded-full text-xs bg-green-100 text-green-800">
                      Completed
                    </span>
                  </div>
                  <div>
                    <span className="font-semibold text-gray-900">Credits Used:</span>
                    <span className="ml-2 text-gray-600">{selectedDesign.creditsUsed}</span>
                  </div>
                  <div>
                    <span className="font-semibold text-gray-900">Created:</span>
                    <span className="ml-2 text-gray-600">{formatDate(selectedDesign.createdAt)}</span>
                  </div>
                  <div>
                    <span className="font-semibold text-gray-900">Updated:</span>
                    <span className="ml-2 text-gray-600">{formatDate(selectedDesign.updatedAt)}</span>
                  </div>
                </div>

                {/* 公开状态控制 */}
                <div className="bg-gray-50 rounded-lg p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <h4 className="font-semibold text-gray-900 mb-1">Public Display Settings</h4>
                      <p className="text-sm text-gray-600">Allow other users to view this design in the public gallery</p>
                    </div>
                    <button
                      onClick={(e) => handleTogglePublicStatus(selectedDesign.id, selectedDesign.isPublic || false, e)}
                      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${
                        selectedDesign.isPublic ? 'bg-blue-600' : 'bg-gray-200'
                      }`}
                    >
                      <span
                        className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                          selectedDesign.isPublic ? 'translate-x-6' : 'translate-x-1'
                        }`}
                      />
                    </button>
                  </div>
                  <div className="mt-2">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                      selectedDesign.isPublic ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                    }`}>
                      {selectedDesign.isPublic ? 'Public' : 'Private'}
                    </span>
                  </div>
                </div>
              </div>

              <div className="mt-6 flex justify-end space-x-3">
                <button
                  onClick={() => handleDeleteDesign(selectedDesign.id)}
                  className="px-4 py-2 text-red-600 border border-red-600 rounded-lg hover:bg-red-50 transition-colors"
                >
                  Delete Design
                </button>
                <button
                  onClick={() => setSelectedDesign(null)}
                  className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </motion.div>
  );
};

export default DesignGallery;